package com.mars.module.system.service.impl;


import com.mars.common.constant.Constant;
import com.mars.common.response.sys.CommonDataResponse;
import com.mars.common.util.Base64;
import com.mars.common.util.IdUtils;
import com.mars.common.util.RSAUtils;
import com.mars.common.util.ValidateCodeUtils;
import com.mars.framework.config.EasyAdminConfig;
import com.mars.framework.redis.RedisCache;
import com.mars.module.system.service.ICommonDataService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author mars
 * @version 1.0
 * @date 2023/10/31 22:27
 */
@Service
public class CommonDataServiceImpl implements ICommonDataService {

    @Resource
    private HttpServletRequest request;

    @Resource
    private HttpServletResponse response;

    @Resource
    private EasyAdminConfig easyAdminConfig;

    @Resource
    private RedisCache redisCache;


    @Override
    public CommonDataResponse acquire() {
        try {
            String uuid = IdUtils.simpleUUID();
            response.setContentType("image/png");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Expire", "0");
            response.setHeader("Pragma", "no-cache");
            ValidateCodeUtils validateCode = new ValidateCodeUtils();
            //直接返回图片
            Map<String, FastByteArrayOutputStream> map = validateCode.getRandomCodeImage(request, easyAdminConfig);
            CommonDataResponse response = new CommonDataResponse();
            response.setUuid(uuid);
            map.forEach((k, v) -> {
                redisCache.setCacheObject(Constant.CAPTCHA_NAME + ":" + uuid, k, 1, TimeUnit.MINUTES);
                response.setImg(Base64.encode(v.toByteArray()));
            });
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
